use crate::mapper;
use sea_orm::{ActiveValue, DatabaseConnection, DeleteResult};
use sky_pojo::{
    dto::category::{CategoryDTO, CategoryPageQueryDTO},
    entities::category,
    vo::PageResult,
};

pub async fn insert(
    db: DatabaseConnection,
    category_dto: CategoryDTO,
    creator: i64,
) -> Result<category::Model, String> {
    let model = category::ActiveModel {
        r#type: category_dto
            .r#type
            .map(ActiveValue::Set)
            .unwrap_or(ActiveValue::not_set())
            .into(), // 处理必填字段
        name: category_dto
            .name
            .map(ActiveValue::Set)
            .unwrap_or_else(|| ActiveValue::Set("Unnamed".to_string())), // 默认值
        sort: category_dto
            .sort
            .map(ActiveValue::Set)
            .unwrap_or(ActiveValue::not_set()),
        status: ActiveValue::Set(Some(1)), // 默认启用状态
        create_user: ActiveValue::Set(Some(creator)),
        update_user: ActiveValue::Set(Some(creator)),
        ..Default::default()
    };

    mapper::category::insert(db, model)
        .await
        .map_err(|err| err.to_string())
}

pub async fn page_query(
    db: DatabaseConnection,
    query_dto: CategoryPageQueryDTO,
) -> Result<PageResult<category::Model>, String> {
    mapper::category::page_query(db, query_dto)
        .await
        .map_err(|err| err.to_string())
}

pub async fn modify_by_id(
    db: DatabaseConnection,
    dto: CategoryDTO,
    modifier: i64,
) -> Result<category::Model, String> {
    let id = dto.id.ok_or_else(|| "ID is required".to_string())?;

    let model = category::ActiveModel {
        id: ActiveValue::Set(id),
        r#type: dto
            .r#type
            .map(ActiveValue::Set)
            .unwrap_or(ActiveValue::not_set())
            .into(),
        name: dto
            .name
            .map(ActiveValue::Set)
            .unwrap_or(ActiveValue::not_set()),
        sort: dto
            .sort
            .map(ActiveValue::Set)
            .unwrap_or(ActiveValue::not_set()),
        status: dto
            .status
            .map(ActiveValue::Set)
            .unwrap_or(ActiveValue::not_set())
            .into(),
        update_user: ActiveValue::set(Some(modifier)),
        ..Default::default()
    };
    mapper::category::modify_by_id(db, id, model)
        .await
        .map_err(|err| err.to_string())
}

pub async fn delete_by_id(
    db: DatabaseConnection,
    category_id: i64,
) -> Result<DeleteResult, String> {
    mapper::category::delete_by_id(db, category_id)
        .await
        .map_err(|err| err.to_string())
}

pub async fn list_by_type(
    db: DatabaseConnection,
    r#type: i32,
) -> Result<Vec<category::Model>, String> {
    mapper::category::list_by_type(db, r#type)
        .await
        .map_err(|err| err.to_string())
}
